package com.cnbbx.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * @author jinge
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter  {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .formLogin().loginPage("/login").defaultSuccessUrl("/cnbbx").permitAll()
                .and().logout().logoutSuccessUrl("/login")
                .and().authorizeRequests()
                .antMatchers("/", "/**/*.css", "/**/*.js").permitAll()
                .antMatchers("/cnbbx/**").hasRole("ADMIN")
                .antMatchers("/eureka/**").hasRole("USER")
                .antMatchers("/actuator/**").hasRole("USER")
                .anyRequest().authenticated().and().httpBasic();
        // 禁用缓存
        http.headers().cacheControl();
        http.headers().contentTypeOptions().disable();
        http.csrf().disable();
    }

    @SuppressWarnings("deprecation")
    @Bean
    public InMemoryUserDetailsManager inMemoryUserDetailsManager() {
        return new InMemoryUserDetailsManager(
                User.withDefaultPasswordEncoder().username("user").password("123456").authorities("ROLE_USER").roles("USER").build(),
                User.withDefaultPasswordEncoder().username("admin").password("123456").authorities("ROLE_ADMIN", "ROLE_USER").roles("ADMIN","USER").build());
    }

}
